<?php

namespace app\admin\model;

use app\model\Model;

class Role extends Model
{
  public $privilege = 'priv';
  public $cids;
  public $id;
  public $db;

  function __construct()
  {
    include 'check.php';
    new Check();

    $this->db = $GLOBALS['db'];
    $this->cids = checkAdminPriv(@$this->privilege); // 判断权限
    $this->id = intval($_GET['id']);
  }

  function index()
  {
    $this->tpl('role', [
      'db' => $this->db,
      'list' => $GLOBALS['db']->getAll("SELECT * FROM role ORDER BY id ASC"),
    ]);
  }

  function add()
  {
    $data = get_post(['r_priv']);

    $res = $this->db->getRow("SELECT * FROM role WHERE r_name = '" . $data['r_name'] . "'");
    // 角色名称防重复
    if (!empty($res)) {
      alert_back('角色重名');
    }

    if ($id = $GLOBALS['db']->exec("INSERT INTO role (r_name,r_priv) VALUES ('" . $data['r_name'] . "', '" . $data['r_priv'] . "')")) {
      admin_log("角色新增 [" . $id . "]");
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'role'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
  }

  function edit()
  {
    $row = $GLOBALS['db']->getRow("SELECT * FROM role WHERE id = '$this->id'");

    $this->tpl('priv', [
      'db' => $this->db,
      'priv' => !empty($row['r_priv']) ? (strpos($row['r_priv'], ',') !== false ? explode(',', $row['r_priv']) : $row['r_priv']) : '',
    ]);
  }

  function edit_action()
  {
    $data = get_post(['rid', 'act']);

    $priv = implode(',', $data); //转为priv字串


    if ($GLOBALS['db']->exec("UPDATE role SET r_priv = '$priv' WHERE id = $this->id")) {
      admin_log("权限编辑 [$this->id]");
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'role'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);

    // // 更新权限至数据库
    // foreach ($_POST as $key => $val) {
    //   if ($val != '' && $key != 'rid' && $key != 'act') {
    //     $arr[$key] = $val;
    //   }
    // }
  }

  function del()
  {
    if ($this->id == 1) {
      alert_back('默认角色不能删除！');
    }

    if ($GLOBALS['db']->exec("DELETE FROM role WHERE id = $this->id")) {
      admin_log("角色删除 [$this->id]");
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'role'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
  }

  function __destruct()
  {
  }
}